import subprocess
import time


def get_cpu_usage_for_process(process_name):
    # 使用 adb shell top 和 grep 获取特定进程的输出
    command = ['adb', 'shell', 'top', '-n', '1', '|', 'grep', process_name]
    result = subprocess.run(command, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, text=True, shell=False)

    # print(f"Command output:\n{result.stdout}")
    if result.stderr:
        print(f"Error: {result.stderr}")
        return None

    if not result.stdout:
        print(f"Process {process_name} not found in top output.")
        return None

    # 解析 grep 的输出以找到 CPU 占用率
    parts = result.stdout.split()

    try:
        cpu_usage = parts[-4]  # 取出倒数第4个元素
        # print(f"CPU Usage: {cpu_usage}")
    except IndexError:
        print("Error: Could not find CPU usage in the line.")

    print(f"cpu_usage: {cpu_usage}")

    if cpu_usage:
        cpu_usage = float(cpu_usage)
        return cpu_usage
    else:
        return None


def get_cpu_usage_for_process_average(process_name, interval, duration):
    """
    模拟获取特定进程的CPU使用率并计算平均值
    :param process_name: 进程名（在这个示例中未使用，因为是模拟）
    :param interval: 获取CPU使用率的间隔（秒）
    :param duration: 总时间（秒）
    :return: CPU使用率的平均值
    """
    total_cpu_usage = 0
    count = 0
    start_time = time.time()

    while True:
        # 模拟获取CPU使用率
        cpu_usage = get_cpu_usage_for_process(process_name)
        total_cpu_usage += cpu_usage
        count += 1

        # 检查是否达到总时间
        if time.time() - start_time >= duration:
            break

        # 等待下一个间隔
        time.sleep(interval / 1000)  # 将秒转换为毫秒

    # 计算平均值
    average_cpu_usage = total_cpu_usage / count
    return average_cpu_usage


# 示例使用：每10毫秒获取一次，共10秒
process_name = "com.didi.dr.fcw"  # 示例进程名
interval = 0.1                   # 100毫秒
duration = 10     # 10秒

# 获取并打印平均值
average_cpu_usage = get_cpu_usage_for_process_average(
    process_name, interval, duration)
print(f"Average CPU Usage for {process_name} in {
      duration}s: {average_cpu_usage:.2f}%")
